﻿using MediatR;
using PublicCommon;
using T_Rbac.Read.APi.Application.Command.Dapartments;
using T_Rbac_Demain;
using T_Rbac_Rep.Interface;

namespace T_Rbac.Read.APi.Application.Handlers.DapartmentHandlers
{
    public class DapartmentTreeSearchBypidHandlers : IRequestHandler<DapartmentTreeSearchBypidCommand, List<PublicTree<Dapartment>>>
    {
        private readonly IDapartment dapartment;

        public DapartmentTreeSearchBypidHandlers(IDapartment dapartment)
        {
            this.dapartment = dapartment;
        }

        public async Task<List<PublicTree<Dapartment>>> Handle(DapartmentTreeSearchBypidCommand request, CancellationToken cancellationToken)
        {
            var list = await dapartment.GetvaluesByResult(x => x.IsDel == false && x.Dpid == request.pid);
            var treelist = new List<PublicTree<Dapartment>>();
            foreach (var item in list.ToArray())
            {
                var tree = new PublicTree<Dapartment>
                {
                    label = item.Dname,
                    level = item.Did,
                    route = null,
                    children = null
                };
                treelist.Add(tree);
                await Getchildren(item.Did, tree);
            }
            var treelists= new List<PublicTree<Dapartment>>
            {
                new PublicTree<Dapartment>
                {
                    label = "全部",
                    level = -1,
                    route = null,
                    children = treelist
                }
            };
            return await Task.FromResult(treelists);
        }

        public async Task Getchildren(int id,PublicTree<Dapartment> publicTree)
        {
            var list = await dapartment.GetvaluesByResult(x => x.Dpid == id && !x.IsDel);
            foreach (var item in list)
            {
                if (publicTree.children==null)
                {
                    publicTree.children = new List<PublicTree<Dapartment>>();
                }
                var substree = new PublicTree<Dapartment>
                {
                    label = item.Dname,
                    level = item.Did,
                    route = null,
                    children = null
                };
                publicTree.children.Add(substree);
                await Getchildren(item.Did, substree);
            }
        }
    }
}
